from Products.KnowledgeEngine.Components.FileUpload.FileUpload import FileUpload, FileUploadExceedsMaximumSizeException, MimeTypeIncorrectException, MIME_TYPES
from Products.KnowledgeEngine.Component import Component
from Products.KnowledgeEngine.Components.FileUpload.UploadFilesystem import UploadFilesystem

import gdata, gdata.docs, gdata.docs.service

class UploadGoogle(UploadFilesystem):
    name  = "UploadGoogle"
    title = "Upload to Google Docs"
   
    @classmethod
    def download(cls, component, assessment):
        """ Downloads the specified document """
        
        componentIdentity = component.getIdentity()
                
        data = assessment.getComponentByIdentityValue( componentIdentity )
        
        url, content_type, filename, file_length = data.split(",")
        
        return component.REQUEST.RESPONSE.redirect( url )
        
        
   
    def sanityCheck(self):
        """ Sanity Check """
        
        filename = self.getFilename()
        extension = filename.split(".").pop().upper()
        if not extension in gdata.docs.service.SUPPORTED_FILETYPES:
            raise MimeTypeIncorrectException( "Google docs does not support this filetype", component=self.context )
        
        UploadFilesystem.sanityCheck( self )
   
    def process(self):
       
        assessment = self.assessment
        
        component_value = ""
        
        filename = self.getFilename()
        if filename:
                            
            self.sanityCheck()
        
            content_type  = self.getContentType()
            file_contents = self.getFileContents()
            file_length   = len( file_contents )
            file_handle   = self.getFileHandle()
            content_type  = self.getContentType()
            
            
            
            
            file_handle.seek(0)
            
            gd_client = gdata.docs.service.DocsService()
            gd_client.auth_token = self.context.getGoogleAuthToken()
                        
            ms = gdata.MediaSource( file_handle=file_handle, content_type=content_type, content_length=file_length, file_name=filename )            
            entry = gd_client.UploadDocument( ms, filename )
                
            url = entry.GetAlternateLink().href
            
            # Construct the file details for storage
            file_details = []
            file_details.append(url)
            file_details.append(content_type)
            file_details.append(filename.replace(',', '_'))
            file_details.append(file_length)
            
            component_value = ','.join(map(lambda value: str(value), file_details))
            
        
        self.setComponentValue( component_value )
            

   
       
   

FileUpload.registerUploadModule( UploadGoogle )